package com.sinszm.es;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sinszm.common.exception.ApiException;
import com.sinszm.es.properties.EsProperties;
import com.sinszm.es.support.EsConstant;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * Es自动化配置
 *
 * @author chenjianbo
 */
@ConditionalOnExpression("${szm.boot.es.enable:false}")
@EnableConfigurationProperties(EsProperties.class)
public class SzmEsAutoConfiguration {

    private final EsProperties esProperties;

    @Autowired
    public SzmEsAutoConfiguration(EsProperties esProperties) {
        this.esProperties = esProperties;
    }

    @Bean(EsConstant.BUILDER_BEAN)
    public RestClientBuilder esBuilder() {
        if (ObjectUtil.isEmpty(esProperties.getNodes())) {
            throw new ApiException("ES节点配置不能为空");
        }
        final String charAt = ":";
        return RestClient.builder(esProperties.getNodes()
                .stream()
                .filter(StrUtil::isNotEmpty)
                .map(node -> {
                    String hostname;
                    int port = esProperties.isSsl() ? 443 : 80;
                    if (node.contains(charAt)) {
                        List<String> list = StrUtil.splitTrim(node, charAt);
                        if (list.size() < 2) {
                            hostname = list.get(0);
                        } else {
                            hostname = list.get(0);
                            port = Integer.parseInt(list.get(1));
                        }
                    } else {
                        hostname = node;
                    }
                    return new HttpHost(hostname, port, esProperties.isSsl() ? "https" : "http");
                }).toArray(HttpHost[]::new));
    }

    /**
     * 配置ES实例
     *
     * @return  ES客户端实例
     */
    @Bean(EsConstant.CLIENT_BEAN)
    public RestHighLevelClient esClient(@Qualifier(EsConstant.BUILDER_BEAN) final RestClientBuilder esBuilder) {
        return new RestHighLevelClient(esBuilder);
    }

}